<template>
    <div class="ctrls">
        <a-button type="primary" @click="editVisible=true">创建相册</a-button>
    </div>
    <div class="photos">
        <a-card hoverable style="width: 300px;display:inline-block;margin:10px 16px 10px 0;" v-for="(item,key) in list" :key="item.id">
            <template #cover>
                <div style="padding:18px;">
                    <img @click="visitAlbum(item.id)"
                        alt="example"
                        v-if="item.cover"
                        :src="imgSiteUrl+item.cover"
                        style="width:262px;height:159px"
                    />
                    <img @click="visitAlbum(item.id)"
                        alt="example"
                        v-else
                        src="~@/assets/album-cover.png"
                    />
                </div>
            </template>
            <template #actions>
                <span key="edit" @click="showEdit(item)"><edit-outlined />编辑</span>
                <span key="del" @click="delAlbum(item.id,key)"><delete-outlined />删除</span>
            </template>
            <a-card-meta :title="item.title" :description="item.desc" @click="visitAlbum(item.id)"></a-card-meta>
        </a-card>
    </div>

    <a-modal v-model:visible="editVisible" :title="formState.id?'编辑相册':'创建相册'" @ok="handleAdd" @cancel="cancelEdit" :centered="true" :width="500" class="edit-photo-album">
        <a-row>
            <a-col :span="4" class="label-name"><span class="red">*</span>相册名称</a-col>
            <a-col :span="20">
                <a-input v-model:value="formState.name" />
            </a-col>
        </a-row>
        
        <div class="blank"></div>
        <a-row>
            <a-col :span="4" class="label-name">相册封面</a-col>
            <a-col :span="20">
                <a-upload list-type="picture-card" action="n" :show-upload-list="false" @change="handlePreview" :before-upload="handleChangeBanner" accept=".png,.jpg">
                    <div v-if="formState.coverPreview===''" class="cover">
                        <img src="@/assets/album-cover.png" alt="" />
                        <div class="text">选择封面</div>
                    </div>
                    <div v-else class="cover">
                        <img :src="formState.coverPreview" alt="" style="width:265px;height:138px" />
                    </div>
                </a-upload>
            </a-col>
        </a-row>

        <div class="blank"></div>
        <a-row>
            <a-col :span="4" class="label-name">相册描述</a-col>
            <a-col :span="20">
                <a-textarea v-model:value="formState.desc" />
            </a-col>
        </a-row>
    </a-modal>
</template>

<script>
import { defineComponent, reactive,createVNode, toRefs, onMounted } from 'vue';
import { EditOutlined,DeleteOutlined,QuestionCircleOutlined } from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue/lib';
import reqwest from 'reqwest';
import { messageTips } from '@/until/tools';
import Http from '@/until/http';
import config from './../until/configs';
import { useRouter } from 'vue-router';
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
export default defineComponent({
    components:{EditOutlined,DeleteOutlined,QuestionCircleOutlined},
    setup() {
        const router = useRouter();
        const state = reactive({
            editVisible:false,
            list:[],
            imgSiteUrl:config.imgSiteUrl
        });
        const formState = reactive({
            id:null,
            name:'',
            desc:'',
            coverPreview:'',
            coverUrl:''
        })

        const handleAdd = ()=>{
            const formData = new FormData();
            formData.append('file', formState.coverUrl);
            formData.append('name', formState.name);
            formData.append('desc', formState.desc);
            let path = config.baseUrl+'/admin/elegant/createAlbum';
            if(formState.id) {
                formData.append('id', formState.id);
                path = config.baseUrl+'/admin/elegant/updateAlbum';
            }
            reqwest({
                url: path,
                method: 'post',
                processData: false,
                data: formData,
                contentType : false,
                success: (res) => {
                    try{
                        let result = JSON.parse(res);
                        if(result.success) {
                            messageTips(result.message,3);
                            state.editVisible = false;
                            cancelEdit();
                            getList();
                        }
                    }catch(e) {
                        console.log(e)
                    }
                },
                error: () => {
                    
                },
            });
        }

        const cancelEdit = ()=>{
            Object.assign(formState,{
                id:null,
                name:'',
                desc:'',
                coverPreview:'',
                coverUrl:''
            })
        }

        const handlePreview= async ({file})=>{
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            formState.coverPreview = file.url || file.preview;
        }

        const handleChangeBanner=(info)=>{
            formState.coverUrl = info;
        }

        const showEdit=(i)=>{
            state.editVisible = true;
            Object.assign(formState,{
                id:i.id,
                name:i.title,
                desc:i.desc,
                coverPreview:i.cover?state.imgSiteUrl+i.cover:'',
                coverUrl:i.cover
            });
        }

        const delAlbum = (id,key)=>{
            Modal.confirm({
                title:'提示',
                icon: createVNode(QuestionCircleOutlined),
                content:'删除相册会连同图片一并删除，确定要删除吗？',
                centered:true,
                okText:'确定',
                cancelText:'取消',
                onOk() {
                    Http.delAlbum({id}).then(res=>{
                        if(res.success) {
                            messageTips(res.message,3);
                            let arr = [...state.list];
                            arr.splice(key,1);
                            Object.assign(state,{
                                list:arr
                            });
                        }
                    })
                }
            })
        }
        const getList = ()=>{
            Http.getPhotoAlbums().then(res=>{
                if(res&&res.list) {
                    state.list = res.list;
                }
            })
        }

        const visitAlbum=(id)=>{
            router.push({path:'/elegant_albumDetail',query:{id}})
        }

        onMounted(()=>{
            getList();
        })
        
        return {
            ...toRefs(state),
            formState,
            handleAdd,
            cancelEdit,
            handlePreview,
            handleChangeBanner,
            showEdit,
            delAlbum,
            visitAlbum
        }
    }
})
</script>

<style lang="scss" scoped>
@import '@/scss/photo_album.scss';
</style>